package com.ophiux.utils.parser.xml;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.utils.common.StringUtil;

public class XMLUtil {

	private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);
	private static final int DEFAULT_BUFFER_SIZE = 1024;

	/**
	 * 读取xml文件
	 * 
	 * @param file
	 * @param encoding
	 * @return
	 */
	@SuppressWarnings("unused")
	public static String getXmlStringFromFile(String file, String encoding) {
		InputStreamReader reader = null;
		StringWriter writer = new StringWriter();
		try {
			if (encoding == null || "".equals(encoding.trim())) {
				reader = new InputStreamReader(new FileInputStream(file), encoding);
			} else {
				reader = new InputStreamReader(new FileInputStream(file));
			}

			char[] buffer = new char[DEFAULT_BUFFER_SIZE];
			int n = 0;
			while (-1 != (n = reader.read(buffer))) {
				writer.write(buffer, 0, n);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (reader != null)
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		// 返回转换结果
		if (writer != null)
			return writer.toString();
		else
			return null;
	}

	/**
	 * 将xml字符串转换成 org.dom4j.Document Description:
	 * 
	 * @param xmStr
	 * @return org.dom4j.Document
	 */
	public static Document parseToDocument(String xmStr) {
		org.dom4j.Document doc = null;
		try {
			return doc = DocumentHelper.parseText(xmStr);

		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			logger.error("xml生成错误 字符串：{}", xmStr);
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * 将Map转换为Xml字符串 Map的键与xml的节点名一致
	 * 
	 * @param map
	 */
	public static String mapToXml(HashMap<String, String> map) {

		if (map == null) {
			return "";
		}
		StringBuffer xmlStr = new StringBuffer();
		for (String key : map.keySet()) {
			String value = map.get(key);
			xmlStr = buildXml(xmlStr, key, value);
		}
		return xmlStr.toString();
	}

	/**
	 * 将Map转换为Xml字符串 Map的键与xml的节点名一致 2019-01-14 sqx支持List的拼接
	 * 
	 * @param map
	 */
	public static String mapToXmlNew(HashMap<String, Object> map) {

		if (map == null) {
			return "";
		}
		StringBuffer xmlStr = new StringBuffer();

		for (Object key : map.keySet()) {
			if (map.get(key) instanceof String) {
				String value = map.get(key) + "";
				xmlStr = buildXml(xmlStr, key + "", value);
			} else if (map.get(key) instanceof List) {
				xmlStr.append("<" + key + ">");
				List list = (List) map.get(key);
				if (list != null && list.size() != 0) {
					for (int i = 0; i < list.size(); i++) {
						xmlStr.append("<ITEM>");
						HashMap<String, Object> listmap = objToMapNew(list.get(i));
						xmlStr.append(mapToXmlNew(listmap));
						xmlStr.append("</ITEM>");
					}
				}
				xmlStr.append("</" + key + ">");
			} else {
				String value = map.get(key) + "";
				xmlStr = buildXml(xmlStr, key + "", value);
			}
		}
//		for(String key:map.keySet()){
//			String value = map.get(key);
//			xmlStr = buildXml(xmlStr, key, value);
//		}
		return xmlStr.toString();
	}

	/**
	 * 组装xml
	 * 
	 * @param xmlStr   数据源xml
	 * @param nodeName 待组装xml节点名
	 * @param value    待组装xml值
	 * @return 组装后的xml
	 */
	public static StringBuffer buildXml(StringBuffer xmlStr, String nodeName, String value) {
		if (StringUtil.isEmpty(value)) {
			value = "";
		}
		xmlStr.append("<" + nodeName + ">").append(value).append("</" + nodeName + ">");
		return xmlStr;
	}

	/**
	 * 将对象转换为map
	 * 
	 * 避免后期UTIL文件迁移 两个文件不在统一地方
	 * 
	 * @param object
	 * @return
	 */
	public static HashMap<String, Object> objToMapNew(Object object) {
		if (object == null) {
			return null;
		}
		HashMap<String, Object> map = new HashMap<String, Object>();
		try {
			BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass());
			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
			for (PropertyDescriptor property : propertyDescriptors) {
				String key = property.getName();
				// 过滤class属性
				if (key.equals("class")) {
					continue;
				}

				// 得到property对应的getter方法
				Method getter = property.getReadMethod();

				Object o = getter.invoke(object);
				if (o instanceof List) {
					List list = (List) o;
					if (list != null && list.size() != 0) {

					} else {
						o = new ArrayList();
					}
				} else {
//					if(o instanceof String) {
					String value = (String) o;
					if (StringUtil.isEmpty(value)) {
						o = "";
					}
//					}
				}

				map.put(key, o);
			}
		} catch (Exception e) {
			System.out.println("transBean2Map Error " + e);
		}
		return map;
	}
}
